import { Injectable, NestMiddleware, ForbiddenException, UnauthorizedException } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { PermissionService } from '../modules/permission/permission.service';
import { RobotService } from '../modules/robot/robot.service';
import { UserService } from '../modules/user/user.service';
import { UserRepository } from '../modules/user/user.repository';
import { RobotRepository } from '../modules/robot/robot.repository';
import { PermissionRepository } from '../modules/permission/permission.repository';

@Injectable()
export class AuthPermissionMiddleware implements NestMiddleware {
  constructor(
    private readonly permissionService: PermissionService,
    private readonly robotService: RobotService,
    private readonly userService: UserService,
    private readonly userRepository: UserRepository,
    private readonly robotRepository: RobotRepository,
    private readonly permissionRepository: PermissionRepository,
  ) { }

  async use(req: Request, res: Response, next: NextFunction) {
    console.log('AuthPermissionMiddleware: Start processing request');
    const session = req.session as any;
    if (!session || !session.userId) {
      console.log('AuthPermissionMiddleware: No userId in session');
      throw new UnauthorizedException('用户未登录');
    }

    // 获取机器人ID，根据不同的路由路径从请求中获取
    let robotId: number;
    if (req.query.robotId) {
      robotId = parseInt(req.query.robotId as string, 10);
      console.log(`AuthPermissionMiddleware: Got robotId ${robotId} from query`);
    } else if (req.body.robotId) {
      robotId = parseInt(req.body.robotId, 10);
      console.log(`AuthPermissionMiddleware: Got robotId ${robotId} from body`);
    }

    if (!robotId) {
      console.log('AuthPermissionMiddleware: No robotId found');
      throw new ForbiddenException('缺少机器人ID');
    }

    try {
      const user = await this.userService.findById(session.userId);
      console.log(`AuthPermissionMiddleware: Found user: ${JSON.stringify(user)}`);
      const robot = await this.robotService.findOne(robotId);
      console.log(`AuthPermissionMiddleware: Found robot: ${JSON.stringify(robot)}`);

      // 获取权限列表
      const permissions = await this.permissionService.findAll(robotId);
      console.log(`AuthPermissionMiddleware: Got permissions: ${JSON.stringify(permissions)}`);

      // 检查用户对该机器人的权限
      const role = this.permissionService.getPermission(user, permissions, robot);
      console.log(`AuthPermissionMiddleware: User role: ${role}`);

      if (role === 'none') {
        console.log('AuthPermissionMiddleware: User has no permission');
        throw new ForbiddenException('无权操作此机器人');
      }

      // 将权限信息添加到请求对象中，供后续处理使用
      req['currentUser'] = user;
      req['currentRobot'] = robot;
      req['userRole'] = role;

      console.log('AuthPermissionMiddleware: Permission check passed, proceeding to next middleware');
      next();
    } catch (error) {
      console.error('AuthPermissionMiddleware error:', error);
      throw error;
    }
  }

  // 检查用户是否对特定机器人有权限
  private async checkPermission(req, robotId) {
    const userId = req.session.userId;
    if (!userId) return false;

    // 获取用户信息
    const userInfo = await this.userRepository.findOne({ where: { id: userId } });
    if (!userInfo) return false;

    // 获取机器人信息
    const robotInfo = await this.robotRepository.findOne({ where: { id: robotId } });
    if (!robotInfo) return false;

    // 获取权限列表
    const permissionList = await this.permissionRepository.find();

    // 使用权限服务来判断用户对机器人的权限
    const permissionRole = this.permissionService.getPermission(userInfo, permissionList, robotInfo);

    // 将用户角色存储在请求中，以便在控制器中使用
    req.userRole = permissionRole;

    // 调试日志
    console.log(`用户 ${userId} 对机器人 ${robotId} 的权限是: ${permissionRole}`);

    return permissionRole !== 'none';
  }
}